/**
 * Copyright 2022 meituan.com Inc. All Rights Reserved.
 */
package org.example.server.context;

import java.io.IOException;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangxiaofan08
 * @version 1.0 2022/3/1
 */
public class UrlClassLoaderContext {
    private static final ConcurrentHashMap<String, URLClassLoader> MAP = new ConcurrentHashMap<>();

    public static void set(String key, URLClassLoader value) {

        URLClassLoader oldClassLoader = MAP.put(key, value);
        unload(oldClassLoader);
    }

    public static void setAll(Map<String, URLClassLoader> map) {
        MAP.putAll(map);
    }

    private static void unload(URLClassLoader classLoader) {
        if (classLoader == null) {
            return;
        }
        try {
            classLoader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //try {
        //    Field ucpField = URLClassLoader.class.getDeclaredField("ucp");
        //    ucpField.setAccessible(true);
        //    URLClassPath ucp = (URLClassPath) ucpField.get(classLoader);
        //
        //    URL[] urLs = classLoader.getURLs();
        //    for (URL url : urLs) {
        //        Method getLoaderMethod = URLClassPath.class.getDeclaredMethod("getLoader", URL.class);
        //        getLoaderMethod.setAccessible(true);
        //        Object jarLoader = getLoaderMethod.invoke(ucp, url);
        //
        //        Method closeMethod = jarLoader.getClass().getDeclaredMethod("close");
        //        closeMethod.setAccessible(true);
        //        closeMethod.invoke(jarLoader);
        //    }
        //} catch (Exception e) {
        //    e.printStackTrace();
        //}
    }

    public static void unload(String key) {
        URLClassLoader classLoader = MAP.get(key);
        unload(classLoader);
        MAP.remove(key);
    }
}
